import time
import matplotlib.pyplot as plt
from generator import generate_test_cases
from alg import insertion_sort, bubble_sort, quick_sort, heap_sort, merge_sort, shell_sort

# 测量排序算法时间
def measure_time(sort_func, arr):
    start_time = time.time()
    sort_func(arr)
    end_time = time.time()
    return end_time - start_time

#测试加可视化
def run_tests():
    test_cases = generate_test_cases()
    algorithms = [insertion_sort, bubble_sort, quick_sort, heap_sort, merge_sort, shell_sort]
    algorithm_names = ["Insertion Sort", "Bubble Sort", "Quick Sort", "Heap Sort", "Merge Sort", "Shell Sort"]
    
    # 存储每种排序算法在每个数据集上的执行时间
    all_times = {case_name: [] for case_name in test_cases}
    
    # 输出每个排序算法的时间
    print("Algorithm Time Comparison:")
    
    for case_name, arr in test_cases.items():
        case_times = []
        print(f"\nTest Case: {case_name}")
        for algorithm, name in zip(algorithms, algorithm_names):
            arr_copy = arr.copy()  # 不修改原始数组
            time_taken = measure_time(algorithm, arr_copy)
            case_times.append(time_taken)
            print(f"{name}: {time_taken:.6f} seconds")
        all_times[case_name] = case_times
    
    # 可视化不同数据情况下的排序算法时间比较
    fig, axes = plt.subplots(5, 2, figsize=(12, 18))  # 创建多个子图
    axes = axes.flatten()  # 展开为一维数组
    
    for i, (case_name, times) in enumerate(all_times.items()):
        axes[i].bar(algorithm_names, times, color="skyblue")
        axes[i].set_title(f"Time Comparison for {case_name}")
        axes[i].set_xlabel("Algorithm")
        axes[i].set_ylabel("Time (seconds)")
        axes[i].tick_params(axis='x', rotation=45)
    
    plt.tight_layout()
    plt.show()

if __name__ == "__main__":
    run_tests()